import { t } from '@src/locales'
import { getRootWindowInitData } from '@src/util/window'
import { hasAuth } from '@src/util/auth'
import { formatDate, isString } from 'pub-bbx-utils'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab } from '@src/util/platform'
import AuthMixin from '@src/mixins/authMixin'
import { jumpContractEdit, jumpContractDetail } from '@src/modules/contract/util/JumpContractUtil.js'

export default {
  name: 'smart-plan-mixin',
  mixins: [AuthMixin],
  data() {
    return {
      statusClassMap: {
        0: 'processing',
        1: 'finished',
        2: 'canceled'
      },
    }
  },
  computed: {
    auth() {
      const rootWindowInitData = getRootWindowInitData()
      return rootWindowInitData?.user?.auth || {}
    },
    /* 新建智能计划权限 */
    hasCreateAuth() {
      return hasAuth(this.auth, 'SMART_PLAN_CREATE')
    },
    /* 编辑智能计划权限 */
    hasEditAuth() {
      return hasAuth(this.auth, 'SMART_PLAN_EDIT')
    },
    /* 查看智能计划权限 */
    hasViewAuth() {
      return hasAuth(this.auth, 'SMART_PLAN_VIEW')
    },
    /* 删除智能计划权限 */
    hasDeleteAuth() {
      return hasAuth(this.auth, 'SMART_PLAN_DELETE')
    },
  },
  methods: {
    getModuleTypeName(type, isDetail) {
      const moduleTypeEnum = {
        'TASK': isDetail ? t('common.base.task') : t('common.base.taskCenter'),
        'EVENT': isDetail ? t('common.base.event') : t('common.base.serviceEvent'),
        'CUSTOMER': t('common.base.customer'),
        'PRODUCT': t('common.base.product'),
        'CONTRACT': t('contract.contract'),
        'PAAS': 'PaaS',
        'ACTIVITY_RESEARCH': t('common.pageTitle.pagePcoperationCustomerExperienceActivityResearchList'),
      }
      return moduleTypeEnum[type]
    },
    getStatusName(status) {
      const statusNameEnum = {
        0: t('common.base.processing'),
        1: t('common.base.usualStatus.finish'),
        2: t('common.base.usualStatus.canceled'),
      }
      return statusNameEnum[status]
    },
    // 获取开始结束时间显示label
    getStartAndEndTimeLabel(setting, type) {
      if (!setting) return ''
      try {
        if (isString(setting)) {
          setting = JSON.parse(setting)
        }
      } catch(error) {
        consol.error('getStartAndEndTimeLabel error:', error)
        return ''
      }
      
      if (setting.bizType == 'specifyTime') {
        return formatDate(setting.specifyTime, 'yyyy-MM-dd HH:mm')
      }
      if (setting.bizType == 'times') {
        return `${t('task.edit.byExecutedNum')}${setting.num}${t('report.mtbtChart.time')}`
      }
      const timeDimensionMap = {
        before: t('common.base.before'),
        behind: t('common.base.after')
      }
      if (type == 'start') {
        return `${this.getModuleTypeName(setting.bizType, true)}${setting.displayName}${timeDimensionMap[setting.timeDimension]}${t('smartPlan.beforeOrBehindDayCreate', {num: setting.day })}`
      }
      return `${this.getModuleTypeName(setting.bizType, true)}${setting.displayName}`
    },
    // 获取重复周期显示label
    getPeriodLabel(setting) {
      if (!setting) return
      try {
        if (isString(setting)) {
          setting = JSON.parse(setting)
        }
      } catch(error) {
        consol.error('getPeriodLabel error:', error)
        return ''
      }
      const periodUnitMap = {
        hour: t('common.base.hour1'),
        day: t('common.time.day'),
        week: t('common.time.week'),
        month: t('common.time.month'),
      }
      if (setting.type == 'fixed') {
        return t('smartPlan.timeExecute', {data: ` ${setting.num} ${periodUnitMap[setting.unit]}`})
      }
      return `${this.getModuleTypeName(setting.bizType, true)}${setting.displayName}${t('smartPlan.behindTimeExecute', {data: `${setting.num} ${periodUnitMap[setting.unit]}`})}`
    },
    // 刷新from tab
    refreshFromTab() {
      let fromId = window.frameElement.getAttribute('fromid')
      this.$platform.refreshTab(fromId)
    },
    /**
     * 关闭并刷新from Tab
    */
    closeAndRefreshFromTab() {
      this.refreshFromTab()
      let id = window.frameElement.dataset.id
      setTimeout(()=>{
        this.$platform.closeTab(id)
      }, 600)
    },
    // 打开工单详情tab
    openTaskTab(taskId, taskNo) {
      if (!taskId || !this.globalIsHaveTaskViewDetailAuth) return
      let fromId = window.frameElement.getAttribute('id')

      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'noHistory=1',
        fromId
      })
    },
    // 打开事件详情tab
    openEventDetailTab(eventId, eventNo) {
      if (!eventId || !this.globalIsHaveEventViewDetailAuth) return
      let fromId = window.frameElement.getAttribute('id')
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: eventId,
        titleKey: eventNo,
        fromId
      })
    },
    // 打开paas详情tab
    openPassTab(row) {
      const {appId, bizNo, planTypeName, templateBizId, bizId, processorInstanceId} = row
      if (!bizId) return

      let fromId = window.frameElement?.getAttribute('id')
      let params = `formId=${templateBizId}&formContentId=${bizId}&appId=${appId}`;
      if (processorInstanceId) params += `&processId=${processorInstanceId}`
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePaasTemplateDetail,
        key: bizNo,
        titleKey: `${planTypeName} ${bizNo || ''}`,
        params,
        fromId
      })
    },
    // 打开活动调研详情tab
    openActivityDetailTab(id, activitiesName) {
      if (!id || !this.auth?.ACTIVITIES_VIEW) return
      let fromId = window.frameElement.getAttribute('id')
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerExperienceActivityResearchView,
        key: id,
        titleKey: `-${activitiesName}`,
        params: `id=${id}`,
        fromId
      })
    },
    // 打开智能计划详情tab
    openSmartPlanDetailTab(planId) {
      if (!planId || !this.hasViewAuth) return
      let fromId = window.frameElement?.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageSmartPlanDetail,
        params: `planId=${planId}`,
        fromId
      })
    },
    // 打开合同详情tab
    openContractDetailTab(row) {
      const { id, contractStatus } = row || {}
      if (!id) return

      // 草稿跳转新建页面
      if (contractStatus == 'DRAFT') {
        jumpContractEdit(row)
      } else {
        jumpContractDetail(row)
      }
    }
  }
}